//
// Created by zhuhun on 2024/3/3.
//
#include "encode.h"
#include "main.h"
#include "spi.h"
#include "stdbool.h"
/**

*Fuction(函数名称):MT6816_ReadAngle(void);

*To do(功能作用):读取mt6816编码器的值(单位0~16184)

*Pin(使用管脚):SPI四个管脚

*var(主要变量):软件片选io口,spi的选择,sample_data即为值;

*hardware(搭载硬件):stm32芯片

*group(组别):电机组

*qq|wechat|tel(选填):q:3038472177;w:222222:t:333333

**/
int MT6816_ReadAngle(void) {
    uint8_t TxData1 = 0x83;
    uint8_t TxData2 = 0x84;
    uint8_t u8Data11 = 0x00;
    uint8_t u8Data12 = 0x00;
    uint16_t sample_data;
    bool pc_flag;
    HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_RESET);
    HAL_SPI_Transmit(&hspi1, &TxData1, 1, 0xffff);
    HAL_SPI_TransmitReceive(&hspi1, &TxData2, &u8Data11, 1, 0xffff);
    HAL_SPI_TransmitReceive(&hspi1, &TxData1, &u8Data12, 1, 0xffff);
    HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_SET);

    sample_data = ((u8Data11 & 0x00FF) << 8) | (u8Data12 & 0x00FF);
    uint8_t h_count = 0;
    for (uint8_t j = 0; j < 16; j++) {
        if (sample_data & (0x0001 << j))
            h_count++;
    }
    if (h_count & 0x01) {
        pc_flag = false;
    } else {
        pc_flag = true;
    }

    if (pc_flag) {
        return (sample_data >> 2);  //前14bits 角度数据
    }
}